var express = require('express');
var router = express.Router();

//加载模型
const CateModel = require('../../models')['Cate']
const NewsModel = require('../../models')['New']
const CommentModel=require('../../models')['Comment']
const UserModel=require('../../models')['User']

//根据新闻id查询新闻详情
router.get('/news/:id', async (req,res)=>{
     try {
         //接收新闻id
         let id = req.params.id;
         //根据分类id获取新闻
         const new_news = await NewsModel.findAll({
             attributes: ['id', 'title', 'content','view_nums','author','createdAt','updatedAt'],
             where: {
                 'id': id
             },
             order: [
                 ['createdAt', 'DESC']
             ],
             include: [
                  {
                      model:CateModel, //关联的模型
                      attributes:['cate_name'] //关联模型表中的字段
                  }
                ],
             limit: 10
         })

         //根据新闻id查询出其对应的评论信息，同时要把评论人的信息查询出来
         let page=req.query.page || 1
         let limit=req.query.limit || 10
         let offset=(page-1)*limit
         const news_comments= await CommentModel.findAll({
             attributes:['id','content','com_time'],
             where:{
                 news_id:id,
                 is_del:1
             },
             order:[
                ['com_time','DESC']
             ],
             offset,
             limit,
             include:[
                  {
                      model: UserModel,
                      attributes:['username','id']
                  }
                ]
         });

         //数据组装
         let data = {
             news_comments,
             news_detail: new_news[0]
         }
         res.cc(200, '请求成功', data)
     } catch (e) {
         res.cc(400, e.message)
     }
})

//更改新闻的访问量
router.patch('/news/:id', async (req,res)=>{
     let id=req.params.id
     try{
        const [num]=await NewsModel.increment({
             view_nums: 1
         }, {
             where: {
                 id
             }
         })
         console.log(num[1]);
         if(num[1]>=1){
             res.cc(200,'修改成功');
         }
        
     }catch(e){
         res.cc(400,e.message)
     }

})

module.exports=router